package org.wupgame.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupgame.model.Connection;
import org.wupgame.model.Room;

@Repository
public interface ConnectionRepository extends JpaRepository<Connection, Long> {
	
	// @Query(value = "select c from Connection c where c.playerId = :playerId")
	// List<Connection> findConnectionsByPlayerId(@Param("playerId") Long playerId);
	
	@Query(value = "select r from Room r join Connection c on r.id = c.roomId where c.playerId = :playerId")
	Room findConnectionByPlayerId(@Param("playerId") Long playerId);
	
	@Transactional
	@Modifying
	@Query(value = "insert into Connection (playerId,roomId) values (:playerId,:roomId)")
	void insertConnection(
		@Param("playerId") Long playerId,
		@Param("roomId") String roomId);
	
	@Transactional
	@Modifying
	@Query(value = "delete from Connection where playerId = :playerId and roomId = :roomId")
	void deleteConnection(
		@Param("playerId") Long playerId,
		@Param("roomId") String roomId);
	
	@Transactional
	@Modifying
	@Query(value = "delete from Connection where roomId = :roomId")
	void deleteAllConnectionsByRoomId(@Param("roomId") String roomId);
}
